package com.sinodata.bsm.cicp.collector.tuxedo;

import java.io.BufferedReader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.log4j.Logger;

import com.sinodata.bsm.cicp.collector.Collector;
import com.sinodata.bsm.cicp.exception.CollectorException;
import com.sinodata.bsm.cicp.util.SnmpConnect;
import com.sinodata.bsm.common.vo.ResPropertyValue;

public class TuxedoSnmpTableCollector extends Collector {
    private final static Logger logger = Logger.getLogger(TuxedoSnmpTableCollector.class);

    @Override
    public List<ResPropertyValue> collect(String ip) throws CollectorException {
        String[] propMetas = getPropMeta();
        String TableOIDS = this.paramMap.get("TableOIDS");
        String community = this.paramMap.get("Community");
        String regex = this.paramMap.get("Regex");
        Pattern pattern = Pattern.compile(regex);
        String result = null;
        List<ResPropertyValue> values = new ArrayList<ResPropertyValue>();
        ResPropertyValue propertyValueX = new ResPropertyValue();
        ResPropertyValue.PropValue[] propValues = new ResPropertyValue.PropValue[getPropMeta().length];
        BufferedReader reader = null;

        try {
            result = SnmpConnect.getValueBySnmpTable(ip, TableOIDS, community);
            StringReader strReader = new StringReader(result);
            reader = new BufferedReader(strReader);
            String readLine = null;
            while ((readLine = reader.readLine()) != null) {
                Matcher matcher = pattern.matcher(readLine);
                if (matcher.find()) {
                    for (int i = 0; i < propValues.length; i++) {
                        propValues[i] = ResPropertyValue.createPropValue(matcher.group(i + 1), propMetas[i]);
                    }
                    propertyValueX.setValues(propValues);
                    values.add(propertyValueX);
                }
            }
        } catch (Exception e) {
            logger.error("snmp MIB file read failed!", e);
            throw new CollectorException(e);
        }
        return values;
    }

    @Override
    public String[] getParamMeta() {
        return new String[] { "TableOIDS", "Community", "Regex", "MatchNum" };
    }

    @Override
    public String[] getPropMeta() {
        int count = Integer.parseInt(this.paramMap.get("MatchNum"));
        String[] propMetas = new String[count];
        for (int i = 1; i <= propMetas.length; i++) {
            propMetas[i - 1] = "$" + i;
        }
        return propMetas;
    }
}
